package com.example.service;

import com.example.entity.*;
import com.example.repository.CategoryRepository;
import com.example.repository.GoodsRepository;
import com.example.repository.OrderDetailRepository;
import com.example.repository.OrderInfoRepository;
import com.example.repository.parameter.LinkEnum;
import com.example.repository.parameter.Operator;
import com.example.repository.parameter.PredicateBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by hongbin on 17/4/1.
 */
@Service
public class OrderService {
    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private OrderInfoRepository orderInfoRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;


    public void saveGoods(Goods good){
        goodsRepository.save(good);
    }
    public OrderInfo saveOrderInfo(OrderInfo orderInfo){
        return orderInfoRepository.save(orderInfo);
    }
    public OrderDetail saveOrderDetail(OrderDetail orderDetail){

        return orderDetailRepository.save(orderDetail);
    }
    public Goods findGoodsById(Long id){
        return goodsRepository.findOne(id);
    }
    public OrderInfo findOrderInfoById(Long id){
        return orderInfoRepository.findOne(id);
    }

    public void deleteGoods(Goods goods){
        goodsRepository.delete(goods);
    }
    public void deleteOrderInfoById(long id){
        orderInfoRepository.delete(id);
    }


    public List<Goods> getGoodsByCid(String cid){

        PredicateBuilder pb  = new PredicateBuilder();

        if (!StringUtils.isEmpty(cid)) {
            pb.add("cid",Long.valueOf(cid), LinkEnum.EQ);
        }

        List<Goods> goods = goodsRepository.findAll(pb.build(), Operator.AND);
        return goods;
    }
    public List<Category> findAllCategory(){
        return categoryRepository.findAll();
    }
    public Page<OrderInfo> findAllOrderInfo(Pageable pages){

        return  orderInfoRepository.findAll(pages);
    }
    /**编辑之前先删除所有的detail子类*/
    public void deleteAllDetails(OrderInfo order){

        List<OrderDetail> orderDetails =null;
        PredicateBuilder pb  = new PredicateBuilder();

        if (!StringUtils.isEmpty(order.getOrderid())) {
            pb.add("orderid",order.getOrderid(), LinkEnum.EQ);
        }
        orderDetails = orderDetailRepository.findAll(pb.build(),Operator.AND);
        if(null == orderDetails) return;
        for(OrderDetail o: orderDetails){
            orderDetailRepository.delete(o);
        }
    }
}
